package encrypt

import (
	"crypto/aes"
	"crypto/cipher"
	"fmt"
	"gitee.com/huanminabc/go-utils/binary"
)

/*
		CBC 加密
		text 待加密的明文
	    key 秘钥
*/
func CBCEncrypterStr(text string, key []byte, iv []byte) string {
	toString := Base64StrEncode(text)
	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println(err)
	}
	// 填充
	paddText := binary.BytePadding([]byte(toString), block.BlockSize())
	blockMode := cipher.NewCBCEncrypter(block, iv)
	// 加密
	result := make([]byte, len(paddText))
	blockMode.CryptBlocks(result, paddText)

	// 返回密文
	return Base64StrEncode(string(result))
}

/*
CBC 解密
encrypter 待解密的密文
key 秘钥
*/
func CBCDecrypterStr(encrypter string, key []byte, iv []byte) string {
	decodeString := Base64StrDecode(encrypter)
	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println(err)
	}
	blockMode := cipher.NewCBCDecrypter(block, iv)
	result := make([]byte, len(encrypter))
	blockMode.CryptBlocks(result, []byte(decodeString))
	// 去除填充
	result = binary.UnBytePadding(result)
	return Base64StrDecode(string(result))
}

func CBCEncrypter(text []byte, key []byte, iv []byte) []byte {
	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println(err)
	}
	// 填充
	paddText := binary.BytePadding([]byte(text), block.BlockSize())
	blockMode := cipher.NewCBCEncrypter(block, iv)
	// 加密
	result := make([]byte, len(paddText))
	blockMode.CryptBlocks(result, paddText)

	// 返回密文
	return result
}

/*
CBC 解密
encrypter 待解密的密文
key 秘钥
*/
func CBCDecrypter(encrypter []byte, key []byte, iv []byte) []byte {
	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println(err)
	}
	blockMode := cipher.NewCBCDecrypter(block, iv)
	result := make([]byte, len(encrypter))
	blockMode.CryptBlocks(result, []byte(encrypter))
	// 去除填充
	result = binary.UnBytePadding(result)
	return result
}
